//
//  DBManage.m
//  UHealth
//
//  Created by gjtxz on 15/1/8.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "DBManage.h"
#import "FMDB.h"
#import "NSString+BloodSugar.h"

#define kLibPath    [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]
#define kDBPath     [NSString stringWithFormat:@"%@/UHealth.sqlite",kLibPath]

//@"BodyTemperatureId",@"UserId",@"UserName",@"MeasureDate",@"BodyTemperatureValue"

static DBManage *_sharedManager = nil;

@implementation DBManage

+ (DBManage *)sharedManager
{
    if (!_sharedManager) {
        _sharedManager = [[DBManage alloc] init];
    }
    return _sharedManager;
}

// INTEGER,TEXT,FLOAT,BLOB(二进制，不改变格式)
//创建表
- (BOOL)createTableWithName:(NSString *)tableName
{
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        BOOL ret = NO;
        NSString *sql;
        if ([tableName isEqualToString:kTemperatureTable]) { //体温记录
        
            //记录Id，用户Id，用户名，测量时间，测量体温值, 上传状态
            sql = [NSString stringWithFormat:
                   @"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER PRIMARY KEY AUTOINCREMENT, %@ INTEGER, %@ TEXT,%@ TEXT,%@ FLOAT, %@ TEXT, %@ INTEGER)",
                   tableName,kBodyTemperatureId, kUserId, kUserName, kMeasureDate, kBodyTemperatureValue, kMeasureIdentifier, kIsUploaded];
        
        }
        else if ([tableName isEqualToString:kYunTemperatureTable]){ //云端体温记录
            
            // 云端体温数据  用户ID 家庭ID 用户名 记录系列 体温 测量时间
            sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER , %@ INTEGER,  %@ TEXT, %@ INTEGER, %@ FLOAT, %@ TEXT, %@ INTEGER)", tableName, kUserId, kFamID, kUserName, kBodyTemperatureId, kBodyTemperatureValue, kMeasureDate, kIsDownloaded];
            
        }
        else if ([tableName isEqualToString:kUserTable]){ // 用户表
            //记录用户基本信心，性别，生日，身高，体重
            sql = [NSString stringWithFormat:
                   @"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER,%@ INTEGER, %@ TEXT, %@ TEXT,%@ INTEGER,%@ TEXT,%@ FLOAT,%@ FLOAT)",
                   tableName,kUserId,kFamID,kUserHeadImg,kUserName,kUserSex,kUserBirthDate,kUserHeight,kUserWeight];
        }
        else if([tableName isEqualToString:kLogTable]){ //日志记录表
            
            // 日志表
            sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER, %@ TEXT, %@ TEXT,%@ INTEGER,%@ TEXT,%@ BLOB)",
                   tableName,kUserId,kDeviceID,kSensorID,kLogType,kLogDate,kLogData];
            
        }
//        else if ([tableName isEqualToString:kBloodSugarTable]) {//血糖记录表
//            
//            sql = [NSString stringWithFormat:
//            @"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER, %@ TEXT, %@ TEXT,%@ INTEGER,%@ FLOAT,%@ FLOAT,%@ FLOAT,%@ INTEGER)",
//            tableName,kUserID,kDeviceID,kSensorID,kCurrentIndex,kCurrentValue,kReferenceValue,kBSValue,kIsUpload];
//            
//        }
//        else if([tableName isEqualToString:kUserRecordTable]){//用户记录表
//            
//            sql = [NSString stringWithFormat:
//            @"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER, %@ TEXT, %@ INTEGER,%@ BLOB)",
//            tableName,kUserID,kRecordBehavior,kRecordType,kRecordTime];
//            
//        }
//        else if([tableName isEqualToString:kUserDailyTable]){//用户日报表
//            
//            sql = [NSString stringWithFormat:
//            @"CREATE TABLE IF NOT EXISTS %@ (%@ INTEGER, %@ BLOB, %@ BLOB, %@ BLOB, %@ BLOB)",
//            tableName,kUserID,kDailyTime,kDailyBreakfastTime,kDailyLunchTime,kDailyDinnerTime];
//        }
        ret = [db executeUpdate:sql];
        [db close];
        return ret;
    }
    return NO;
}

//增
- (BOOL)insertData:(id)data andTable:(NSString *)tableName
{
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        BOOL ret = NO;
        NSString *sql;
        if([tableName isEqualToString:kTemperatureTable]){
        
            BodyTemperatureObj *m = (BodyTemperatureObj *)data;
            NSString *measureDateStr = [NSString stringFromDate:m.measureDate];
            sql = [NSString stringWithFormat:
                   @"INSERT INTO %@(%@,%@,%@,%@,%@,%@) VALUES ('%ld', '%@', '%@', '%f', '%@', '%d')",
                   tableName, kUserId, kUserName, kMeasureDate, kBodyTemperatureValue, kMeasureIdentifier, kIsUploaded, m.userId, m.userName, measureDateStr, m.bodyTemperatureValue, m.measureIdentifier, m.isUploaded];
            
        }
        else if([tableName isEqualToString:kYunTemperatureTable]){
            
            BodyTemperatureObj *m = (BodyTemperatureObj *)data;
            NSString *measureDateStr = [NSString stringFromDate:m.measureDate];
            sql = [NSString stringWithFormat:
                   @"INSERT INTO %@(%@,%@,%@,%@,%@) VALUES ('%ld', '%@', '%@', '%f', '%d')",
                   tableName, kUserId, kUserName, kMeasureDate, kBodyTemperatureValue, kIsDownloaded, m.userId, m.userName, measureDateStr, m.bodyTemperatureValue, m.isDownloaded];
            
        }
        else if ([tableName isEqualToString:kUserTable]){
            UserObj * u = (UserObj *)data;
            
            sql = [NSString stringWithFormat:
                   @"INSERT OR REPLACE INTO %@(%@,%@,%@,%@,%@,%@,%@,%@) VALUES ('%ld', '%d', '%@', '%@', '%d', '%@', '%f', '%f')",
                   tableName,kUserId,kFamID,kUserHeadImg,kUserName,kUserSex,kUserBirthDate,kUserHeight,kUserWeight,u.userID,u.famID,
                   u.headImg,u.name,u.sex,u.birthDate,u.height,u.weight];
            
            
        }
//        else if ([tableName isEqualToString:kBloodSugarTable]) {
//
//            BSDataObj *bs = (BSDataObj*)data;
//            sql = [NSString stringWithFormat:
//                   @"INSERT INTO %@(%@,%@,%@,%@,%@,%@,%@,%@) VALUES ('%d', '%@', '%@', '%d', '%d', '%f', '%f', '%d')",
//                   tableName,kUserID,kDeviceID,kSensorID,kCurrentIndex,kCurrentValue,kReferenceValue,kBSValue,kIsUpload,
//                   bs.userID,bs.deviceID,bs.sensorID,bs.currentIndex,bs.currentValue,bs.referenceValue,bs.BSValue,bs.isUpload];
//            
//        }
        else if([tableName isEqualToString:kLogTable]){
           
            LogDataObj *log = (LogDataObj*)data;
            sql = [NSString stringWithFormat:
                   @"INSERT INTO %@(%@,%@,%@,%@,%@,%@) VALUES ('%ld', '%@', '%@', '%d', '%@' ,'%@')",
                    tableName,kUserId,kDeviceID,kSensorID,kLogType,kLogDate,kLogData,
                    log.userID,log.deviceID,log.sensorID,log.logType,log.logDate,log.logData];
            
        }
//        else if([tableName isEqualToString:kUserRecordTable]){
//            
//            UserRecordObj *rec = (UserRecordObj*)data;
//            sql = [NSString stringWithFormat:
//                   @"INSERT INTO %@(%@,%@,%@,%@) VALUES ('%d', '%@', '%d', '%@')",
//                   tableName,kUserID,kRecordBehavior,kRecordType,kRecordTime,
//                   rec.userID,rec.recordBehavior,rec.recordType,rec.recordTime];
//            
//        }
//        else if([tableName isEqualToString:kUserRecordTable]){
//            
//            UserDailyObj *dai = (UserDailyObj*)data;
//            sql = [NSString stringWithFormat:
//                   @"INSERT INTO %@(%@,%@,%@,%@,%@) VALUES ('%d', '%@', '%@', '%@', '%@')",
//                   tableName,kUserID,kDailyTime,kDailyBreakfastTime,kDailyLunchTime,kDailyDinnerTime,
//                   dai.userID,dai.dailyTime,dai.dailyBreakfastTime,dai.dailyLunchTime,dai.dailyDinnerTime];
//            
//        }
        ret = [db executeUpdate:sql];
        [db close];
        return ret;
    }
    return NO;
}

//删
- (BOOL)deleteDataFromTable:(NSString *)tableName andConditions:(NSString *)conditionStr
{
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        BOOL ret = NO;
        NSString *sql;
        if (conditionStr == nil || [conditionStr isEqualToString:@""]) {//无条件删除所有
            sql = [NSString stringWithFormat:@"DELETE FROM %@",tableName];

        } else {
            sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@",tableName,conditionStr];

        }
        ret = [db executeUpdate:sql];
        [db close];
        return ret;
    }
    return NO;
}

//改
- (BOOL)updateData:(id)data andTable:(NSString *)tableName andConditions:(NSString *)conditionStr
{
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        BOOL ret = NO;
        NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@",tableName,data,conditionStr];
        ret = [db executeUpdate:sql];
        
        [db close];
        return ret;
    }
    return NO;
}

//查
- (id)queryDataFromTable:(NSString *)tableName andConditions:(NSString *)conditionStr
{
    FMDatabase *db = [FMDatabase databaseWithPath:kDBPath];
    if ([db open]) {
        NSMutableArray *dataArr = [NSMutableArray array];
        
        FMResultSet *result = nil;
        NSString *sql;
        if (conditionStr == nil || [conditionStr isEqualToString:@""]) {//无条件查询所有的数据
            sql = [NSString stringWithFormat:@"SELECT * FROM %@",tableName];
            
        } else {
            sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@",tableName,conditionStr];
        }
        result = [db executeQuery:sql];
        while ([result next]) {
            if ([tableName isEqualToString:kTemperatureTable]) {
                
                BodyTemperatureObj *m  = [[BodyTemperatureObj alloc] init];
                m.bodyTemperatureId    = [result longForColumn:kBodyTemperatureId];
                m.userId               = [result longForColumn:kUserId];
                m.userName             = [result stringForColumn:kUserName];
                m.measureDate          = [NSDate dateFromString:[result stringForColumn:kMeasureDate]];
                m.bodyTemperatureValue = [result doubleForColumn:kBodyTemperatureValue];
                m.measureIdentifier    = [result stringForColumn:kMeasureIdentifier];
                m.isUploaded           = [result intForColumn:kIsUploaded];
                [dataArr addObject:m];
            }else if ([tableName isEqualToString:kYunTemperatureTable]) {
                
                BodyTemperatureObj *m  = [[BodyTemperatureObj alloc] init];
                m.bodyTemperatureId    = [result longForColumn:kBodyTemperatureId];
                m.userId               = [result longForColumn:kUserId];
                m.userName             = [result stringForColumn:kUserName];
                m.measureDate          = [NSDate dateFromString:[result stringForColumn:kMeasureDate]];
                m.bodyTemperatureValue = [result doubleForColumn:kBodyTemperatureValue];
                m.isDownloaded         = [result intForColumn:kIsDownloaded];
                [dataArr addObject:m];
            }else if ([tableName isEqualToString:kUserTable]){
                
                UserObj *u = [[UserObj alloc]init];
                u.userID            = [result longForColumn:kUserId];
                u.famID             = [result intForColumn:kFamID];
                u.headImg           = [result stringForColumn:kUserHeadImg];
                u.name              = [result stringForColumn:kUserName];
                u.sex               = [result intForColumn:kUserSex] ;
                u.birthDate         = [result stringForColumn:kUserBirthDate];
                u.height            = [result doubleForColumn:kUserHeight];
                u.weight            = [result doubleForColumn:kUserWeight];
                [dataArr addObject:u];
                
            }
//            else if ([tableName isEqualToString:kBloodSugarTable]) {
//
//                BSDataObj *b = [[BSDataObj alloc]init];
//                b.userID        = [result intForColumn:kUserID];
//                b.deviceID      = [result stringForColumn:kDeviceID];
//                b.sensorID      = [result stringForColumn:kSensorID];
//                b.currentIndex  = [result intForColumn:kCurrentIndex];
//                b.currentValue  = [result intForColumn:kCurrentValue];
//                b.referenceValue= [result doubleForColumn:kReferenceValue];
//                b.BSValue       = [result doubleForColumn:kBSValue];
//                b.isUpload      = [result intForColumn:kIsUpload];
//                [dataArr addObject:b];
//                
//            }
            else if ([tableName isEqualToString:kLogTable]) {
                
                LogDataObj *log = [[LogDataObj alloc]init];
                log.userID      = [result intForColumn:kUserId];
                log.deviceID    = [result stringForColumn:kDeviceID];
                log.sensorID    = [result stringForColumn:kSensorID];
                log.logType     = [result intForColumn:kLogType];
                log.logDate     = [result stringForColumn:kLogDate];
                log.logData     = [result dataForColumn:kLogData];
                [dataArr addObject:log];

            }
//            else if ([tableName isEqualToString:kUserRecordTable]) {
//                
//                UserRecordObj *rec  = [[UserRecordObj alloc]init];
//                rec.userID          = [result intForColumn:kUserID];
//                rec.recordBehavior  = [result stringForColumn:kRecordBehavior];
//                rec.recordType      = [result intForColumn:kRecordType];
//                rec.recordTime      = [result dateForColumn:kRecordTime];
//                [dataArr addObject:rec];
//                
//            }
//            else if ([tableName isEqualToString:kUserRecordTable]) {
//                
//                UserDailyObj *dai  = [[UserDailyObj alloc]init];
//                dai.userID                  = [result intForColumn:kUserID];
//                dai.dailyTime               = [result dateForColumn:kDailyTime];
//                dai.dailyBreakfastTime      = [result dateForColumn:kDailyBreakfastTime];
//                dai.dailyLunchTime          = [result dateForColumn:kDailyLunchTime];
//                dai.dailyDinnerTime         = [result dateForColumn:kDailyDinnerTime];
//                [dataArr addObject:dai];
//                
//            }
        }
//        [db close];
        return dataArr;
    }
    return nil;
}



//获取某个用户
-(UserObj *)getUserWithID:(int)ID{
    
    NSString *conStr = [NSString stringWithFormat:@"%@ = '%d' and %@ = '%d'",kUserId,(int)kNetID,kFamID,ID];
    NSArray *arr = [[DBManage sharedManager] queryDataFromTable:kUserTable andConditions:conStr];
    if (arr.count) {
        return arr[0];
    }
    return nil;
    
}

//获取默认用户
-(UserObj *) getDefUser
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    //获取默认用户信息
    int userId = (int)[def integerForKey:kLastUserID];
    return  [[DBManage sharedManager] getUserWithID:userId];
//    return  [[DBManage sharedManager] getUserWithID:kGetFamID];
}


@end
